
import { baseURL } from './data.js';
import {
	applyId
} from './data.js';

const getApplyId = () => {
	return new Promise((resolve) => {
		uni.getProvider({
			service: "oauth",
			success: async function(res) {
				resolve(applyId[res.provider[0]]);
			},
		});
	})
	
}

const request = (path, data = {}, extraParams = {}) => {
	const token = uni.getStorageSync('Authorization_token');
	const loginProvider = uni.getStorageSync('loginProvider');
	const _extraParams = {
		...extraParams,
	}
	const {
		loadingText,
		hideLoading,
	} = extraParams;
	delete _extraParams.loadingText;
	delete _extraParams.hideLoading;
	// uni.removeStorageSync('Authorization_token');
	// console.log('获取到Token', token);
	!hideLoading && uni.showLoading({
		title: loadingText || '加载中'
	})
	return new Promise(async (resolve, reject) => {
		// console.log(uni.getSystemInfoSync(), 'uni.getSystemInfoSync().uniPlatform');
		const _applyId = await getApplyId();
		uni.request({
			url: baseURL + path,
			method: 'POST',
			data: {
				applyId: _applyId,
				...data,
			},
			header: {
				Authorization: 'Bearer ' + token,
			},
			async success(res) {
				console.log('interface success', res);
				if (!res.data) {
					uni.$u.toast('网络请求失败');
					reject({});
				} else if (res.data.status === 401) { //登录超时，自动重新登录
					await uni.$checkLogin();
					// 再发一遍接口
					let againRes = request(path, data, extraParams);
					resolve(againRes);
				} else if (res.data.status === 200) {
					resolve(res.data);
				} else {
					if(res.data.message){
						uni.$u.toast(res.data.message);
					}
					reject(res.data);
				}

			},
			fail(error) {
				console.log(error)
				reject(error);
			},
			complete() {
				!hideLoading && uni.hideLoading()
			},
			..._extraParams, //支持传入其他的参数
		})
	})
};
export default request;